package com.company;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class UDPServer {

    public static void main(String[] args) throws Exception{
        DatagramSocket ds = new DatagramSocket(4603);

        while(true) {
            byte[] buf = new byte[1024];
            DatagramPacket dp = new DatagramPacket(buf,buf.length);
            ds.receive(dp);
            new Thread(new ThreadServerHandler(ds, dp)).start();
        }


    }
}

class ThreadServerHandler implements Runnable{

    private DatagramSocket ds;
    private DatagramPacket dp;

    public ThreadServerHandler(DatagramSocket ds, DatagramPacket dp){
        this.ds = ds;
        this.dp = dp;
    }

    @Override
    public void run() {
        try {
            String str = new String(dp.getData(),0,dp.getLength());
            System.out.println("从" + dp.getAddress().getHostAddress() + ":" + dp.getPort() + "接收到信息：" + str);
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入传给客户端的信息：");
            String ans = sc.nextLine();
            byte[] buf = ans.getBytes();
            int port = dp.getPort();
            InetAddress address = dp.getAddress();
            DatagramPacket toClientPacket = new DatagramPacket(buf,buf.length,address,port);
            ds.send(toClientPacket);
            System.out.println("向客户端" + dp.getAddress().getHostAddress() + ":" + dp.getPort() + "发送信息");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

